<?php

namespace app\admin\controller;

use app\common\model;
use app\common\model\Order as OrderModel;
use app\common\model\Mall;

use app\service\OrderService;
use app\service\ThirdcainiaoService;
use app\service\ThirdService;
use app\service\UserService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Db;
use think\Exception;
use app\common\model\UnionOrder;


class Order extends Base
{
    public $orderModel;
    public $unionOrderModel;

    public function __construct()
    {
        parent::__construct();
        $this->orderModel = new model\Order;
        $this->unionOrderModel = new UnionOrder();
    }

    /* 
     列表
     */
    public function list()
    {
        $where = array();
        $input = input();
        $page = max(input('page'), 1);
        $size = 20;
        $whereArr = $this->buildQuery();
        if ($input['excel']) {
            //导出excel
            $orderList = $this->orderModel->where($whereArr[0], $whereArr[1])->order('pay_time desc,create_time desc')->select()->toArray();
            if (!$orderList) {
                return returnJson(1, '无数据');
            }
            if (!($input['create_time_start'] && $input['create_time_end']) && !($input['send_time_start'] && $input['send_time_end']) && !($input['pay_time_start'] && $input['pay_time_end'])) {
                return returnJson(1, '必须选择一个时间区间');
            }
            if ($input['create_time_start'] && $input['create_time_end'] && (strtotime($input['create_time_end']) - strtotime($input['create_time_start'])) > 31 * 24 * 3600) {
                return returnJson(1, '订单创建时间区间不能超过31天');
            }
            if ($input['send_time_start'] && $input['send_time_end'] && (strtotime($input['send_time_end']) - strtotime($input['send_time_start'])) > 31 * 24 * 3600) {
                return returnJson(1, '订单发货时间区间不能超过31天');
            }
            if ($input['pay_time_start'] && $input['pay_time_end'] && (strtotime($input['pay_time_end']) - strtotime($input['pay_time_start'])) > 31 * 24 * 3600) {
                return returnJson(1, '订单支付时间区间不能超过31天');
            }
            $file = $this->exportExcel($orderList);
            return returnJson(0, '', $file);
        }
        if (input('zz')) {
            pr($whereArr);
        }
        $orderList = $this->orderModel->where($whereArr[0], $whereArr[1])->order('pay_time desc,create_time desc')->page($page, $size)->select()->toArray();
        $total = $this->orderModel->where($whereArr[0], $whereArr[1])->count();
        if (!$orderList) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach ($orderList as $k => $v) {
            $orderList[$k]['goods_list'] = json_decode($v['goods_list'], true);
            foreach ($orderList[$k]['goods_list'] as $kk => $vv) {
                $orderList[$k]['goods_list'][$kk]['picture'] = $vv['picture'] ? tomedia($vv['picture']) : '';
            }
            $orderList[$k]['userInfo'] = UserService::S()->findUser(['id' => $v['uid']], ['nickname', 'id']);
            if ($v['refer_uid']) {
                $orderList[$k]['referInfo'] = UserService::S()->findUser(['id' => $v['refer_uid']], ['nickname', 'id']);
            } else {
                $orderList[$k]['referInfo'] = '';
            }
            $status_text = '';//0待支付,1待发货,,2完成,3.待退款 4已退款,5发货,0未完成,6订单关闭,

            $orderList[$k]['status_text'] = $this->getStatusText($v['checked']);
            $orderList[$k]['mallInfo'] = Mall::getOneById($v['mall_id'], 'id,name,money');
            $orderList[$k]['student'] = model\Student::getValue(['id'=>$v['sid']],'name');
            /* if($v['picture_list']) {
                $pics = json_decode($v['picture_list'],true);
                foreach($pics as $kk=>$vv) {
                    $pics[$kk]['url'] = tomedia($vv['path']);
                }
                $orderList[$k]['picture_list'] = $pics;
            }
            $orderList[$k]['picture'] = tomedia($v['picture']); */
        }
        return returnJson(0, '', [
            'list' => $orderList,
            'size' => $size,
            'total' => $total
        ]);
    }


    /* 发货 */
    public function send()
    {
        $input = input();
        $order = OrderModel::getOne(['id' => $input['id']]);

        //判断订单商城余
        $mall = Mall::getOne(array('id' => $order['mall_id']));
        if ($mall['money'] <= 0 && $mall['id'] != 0) {
            //$this->ajax(1,$mall['name']."余额不足不能发货");
        }
        if (!$order) {
            return returnJson(1, '订单不存在');
        }
        if (!in_array($order['checked'], [1, 2, 5])) {
            return returnJson(1, '当前状态无法发货');
        }
        if (!$input['express_no'] || !$input['express_com']) {
            return returnJson(1, '请填写完整物流信息');
        }
        $res = OrderService::S()->sendOrder($order, $input);
        if ($res === true) {
            return returnJson(0, '已发货');
        } else {
            return returnJson(1, $res);
        }
    }

    /* 查询物流信息 */
    public function wuliu()
    {
        $input = input();
        $order = OrderModel::getOne(['id' => $input['id']]);
        if (!$order) {
            return returnJson(1, '订单不存在');
        }
        if (!$order['express_no'] || !$order['express_com']) {
            return returnJson(1, '无物流信息');
        }
        $res = OrderService::S()->getWuliu($order['express_no'], $order['express_com']);
        if ($res) {
            return returnJson(0, '', $res);
        }
        return returnJson(1, '无物流信息');
    }

    protected function exportExcel($list)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $arrData = [
            ['订单ID', '订单号', '用户ID', '用户昵称', '状态', '总金额', '在线支付', '佣金支付', '积分支付', '订单信息', '创建时间', '支付时间', '发货时间',
                '快递公司', '快递单号', '收货人姓名', '收货人手机号', '省', '市', '区', '详细地址']
        ];
        foreach ($list as $k => $v) {
            $v['userInfo'] = UserService::S()->findUser(['id' => $v['uid']], ['nickname', 'id']);
            $goodsList = json_decode($v['goods_list'], true);
            $status_text = $this->getStatusText($v['checked']);
            $goodsString = '';
            foreach ($goodsList as $goods) {
                $goodsString .= "{$goods['name']}:{$goods['goods_num']}\n";
            }
            $arrData[] = [
                $v['id'], $v['order_sn'], $v['uid'], $v['userInfo']['nickname'], $status_text, $v['all_money'], $v['pay_money'], $v['yonjin_money'], $v['score_money'],
                $goodsString,
                $v['create_time'], $v['pay_time'], $v['send_time'], $v['express_com'], $v['express_no'], $v['delivery_name'], $v['delivery_mobile'],
                $v['delivery_province'], $v['delivery_city'], $v['delivery_county'], $v['delivery_address']
            ];
        }
        $sheet->fromArray($arrData, NULL);
        $writer = new Xlsx($spreadsheet);
        $name = '订单信息-' . date('Y-m-d') . '-' . time() . ".xlsx";
        $path = ROOT_PATH . "public" . DS . "cache" . DS . $name;
        $writer->save($path);
        return request()->domain() . "/cache/" . $name;
    }

    protected function buildQuery()
    {
        $input = input();
        $where = [];
        $query = "1 ";
        if ($input['id']) {
            $where['id'] = $input['id'];
            $query .= " AND id=:id";
        }
        if ($input['order_sn']) {
            $where['order_sn'] = $input['order_sn'];
            $query .= " AND order_sn=:order_sn";
        }
        if ($input['uid']) {
            $where['uid'] = $input['uid'];
            $query .= " AND uid=:uid";
        }
        if ($input['shop_type']) {
            $where['shop_type'] = $input['shop_type'];
            $query .= " AND shop_type=:shop_type";
        } else {
            $where['shop_type'] = 1;
            $query .= " AND (shop_type=:shop_type or shop_type=5)";
        }
        if (isset($input['checked'])) {
            if ($input['checked'] != 'all') {
                $where['checked'] = $input['checked'];
                $query .= " AND checked=:checked";
            }
        }
        if ($input['create_time_start']) {
            $where['create_time_start'] = strtotime($input['create_time_start']);
            $query .= " AND create_time>=:create_time_start";
        }
        if ($input['create_time_end']) {
            $where['create_time_end'] = strtotime($input['create_time_end']);
            $query .= " AND create_time<=:create_time_end";
        }
        if ($input['pay_time_start']) {
            $where['pay_time_start'] = strtotime($input['pay_time_start']);
            $query .= " AND pay_time>=:pay_time_start";
        }
        if ($input['pay_time_end']) {
            $where['pay_time_end'] = strtotime($input['pay_time_end']);
            $query .= " AND pay_time<=:pay_time_end";
        }
        if ($input['send_time_start']) {
            $where['send_time_start'] = strtotime($input['send_time_start']);
            $query .= " AND send_time>=:send_time_start";
        }
        if ($input['send_time_end']) {
            $where['send_time_end'] = strtotime($input['send_time_end']);
            $query .= " AND send_time<=:send_time_end";
        }
        return [$query, $where];
    }

    protected function getStatusText($status)
    {
        switch ($status) {
            case 0:
                $status_text = '待付款';
                break;
            case 1:
                $status_text = '待发货';
                break;
            case 2:
                $status_text = '已完成';
                break;
            case 3:
                $status_text = '待退款';
                break;
            case 4:
                $status_text = '已退款';
                break;
            case 5:
                $status_text = '已发货';
                break;
            case 6:
                $status_text = '订单关闭';
                break;
            case 7:
                $status_text = '已评价';
                break;
        }
        return $status_text;
    }


    //打印订单
    public function printOrder()
    {
        try {
            $order_id = input('get.order_id');
            $orderPrintModel = Db::name('orderprint');//Db:name('');
            $order_where['id'] = array('in', $order_id);
            $order_list = OrderService::S()->orderList($order_where);
            if (empty($order_list)) {
                $this->ajax(202, '订单不存在');
            }
            $printed_nums = '';
            $error_order_ids = '';
            foreach ($order_list as $ok => $ov) {  //循环请求打印
                $print_re_where['order_id'] = $ov['id'];
                $print_re = $orderPrintModel->where($print_re_where)->find();
                $remark = '';
                $goods = json_decode($ov['goods_list'], true);
                $num = 0;

                foreach ($goods as $k => $v) {
                    //$v_guige=unserialize($v['guige_new']);
                    $guige_name = '';
                    $num += $v['goods_num'];
                    $remark .= "【";
                    $remark .= $v['goods_num'] . "件" . "//[规格：{$v['name']}]";
                    $remark .= '】.-';

                }
                $remark .= "总计：{$num}件";
                $array['remark'] = $remark;

                if (empty($ov['remark'])) {
                    $ov['khnote'] = '无';
                }
                //$remark.="【用户备注信息:".$ov['khnote']."】";
                $remark .= "【用户备注信息:" . $ov['remark'] . "】";
                if ($print_re && $print_re['status'] == 1) {//已有订单未打印
                    $print_data[$ov['id']]['data'] = json_decode($print_re['print_data'], true);
                    $print_data[$ov['id']]['waybill_code'] = $print_re['waybill_code'];//json_decode($print_re['print_data'],true);
                    $print_data[$ov['id']]['order_id'] = time() . "_" . $ov['id'];
                    $print_data[$ov['id']]['remark'] = $remark;
                } else {
                    $re = ThirdcainiaoService::S()->buildOrder($ov['id'], $print_re);
                    if ($re['code'] == 200) {
                        $print_data[$ov['id']]['data'] = json_decode($re['data'], true);
                        $print_data[$ov['id']]['waybill_code'] = $re['waybill_code'];
                        $print_data[$ov['id']]['order_id'] = $ov['id'];
                        $print_data[$ov['id']]['remark'] = $remark;
                    } else {
                        $error_order_ids .= $ov['id'] . ',';
                    }
                }
            }
            $pdata = array(
                "dayin" => $print_data,
                "all_nums" => count($print_data),
                "printed_nums" => $printed_nums,
                'printer' => config('printer_name'),
                'error_order' => $error_order_ids,
            );
            /*if($printed_nums){
                $msg = "即将打印".$pdata['all_nums']."个面单,其中包含已经打印过的订单".$printed_nums."个,是否继续打印?";
            }else{
                $msg = "即将打印".$pdata['all_nums']."个面单,是否继续打印?";
            }*/
            $msg = "即将打印{$pdata['all_nums']}个面单";
            $this->ajax(0, $msg, $pdata);
        } catch (Exception $ex) {
            //dump($ex->getMessage());
            $this->ajax(1, 'Exception', $ex->getMessage());
        }

    }

    //取消电子面单
    public function cancelOrder()
    {
        $order_id = input('get.order_id');
        //dump($order_id);die;
        $re = ThirdcainiaoService::S()->discard($order_id);
        if ($re['code'] == 200) {
            $this->ajax(0, '取消成功', '', '/admin/order/index?order_id=' . $order_id);
        } else {
            $this->ajax(1, '取消失败');
        }
    }


    /* 退款 */
    public function refund()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, '订单不存在');
        }
        $res = OrderService::S()->refundOrder($input['id']);
        if ($res === true) {
            return returnJson(0, '退款成功');
        } else {
            return returnJson(1, $res);
        }
    }

    /* 生态商城订单 */
    public function taokeList()
    {
        $input = input();
        $page = max($input['page'], 1);
        $size = 20;
        $where = $this->buildTaokeQuery();
        $orderList = UnionOrder::getPage($where, $page, $size);
        $total = UnionOrder::getCount($where);
        if (!$orderList) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0,
                'census' => 0
            ]);
        }
        $where .= " and ((type='jd' and status in(16,17,18)) or (type='pdd' and status in (0,1,2,5)))";
        foreach ($orderList as $k => $v) {
            $orderList[$k]['content'] = json_decode($v['content'], true);
            if ($v['type'] == 'jd') {
                $orderList[$k]['status_text'] = UnionOrder::getOrderStatusText($v['status']);
            } else if ($v['type'] == 'pdd') {
                $orderList[$k]['status_text'] = UnionOrder::getOrderPddStatusText($v['status']);
                $orderList[$k]['content']['skuList'][0]['skuName'] = $orderList[$k]['content']['goods_name'];
            }
            $orderList[$k]['userInfo'] = UserService::S()->findUser(['id' => $v['union_uid']], ['nickname', 'id']);
            $orderList[$k]['mall_money'] = round($v['money'] * config('union_jd_mall_bili'), 2);
        }
        return returnJson(0, '', [
            'list' => $orderList,
            'size' => $size,
            'total' => $total,
            'census' => $this->unionOrderModel->where($where)->sum('money')
        ]);
    }

    /**
     * 查询生态商城订单查询条件过滤
     */
    protected function buildTaokeQuery(){
        $input = input('');
        $where = '';
        $start_time = $input['create_start_time']?strtotime($input['create_start_time']):0;
        $end_time = $input['create_end_time']?strtotime($input['create_end_time']):time();
        $where .= "create_time between {$start_time} and {$end_time} ";
        if($input['id']){
            $where .= " and id = {$input['id']} ";
        }
        if($input['order_id']){
            $where .= "and order_id={$input['order_id']} ";
        }
        if ($input['union_uid']){
            $where .= "and union_uid={$input['union_uid']} ";
        }
        if ($this->manager['mall_id']) {
            $mall_id = $this->manager['mall_id'] + 100;
            $where .= "and union_mall_id={$mall_id}";
        }
        return $where;
    }

}
